﻿using SCG.WinForms;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;

namespace SCG.TurboSprite
{
    public class BreakingBitmapParticle : ExplosionParticle
    {
        //constructor
        public BreakingBitmapParticle(BreakingBitmapExplosionSprite explosion)
            : base(explosion)
        {
            _rotation = Sprite.RND.Next(10) - 5;
            _rotation *= (float)Sprite.RND.NextDouble();

            //create a randomly sized image from the source image
            int startDiam = explosion.StartDiameter;
            int endDiam = explosion.EndDiameter;
            if (endDiam <= startDiam)
                endDiam = startDiam + 1;

            int range = endDiam - startDiam;
            int width = Sprite.RND.Next(range) + startDiam;
            int height = Sprite.RND.Next(range) + startDiam;
            try
            {
                if (width > explosion.Image.Width)
                    width = explosion.Image.Width;
                if (height > explosion.Image.Height)
                    height = explosion.Image.Height;

                int w = Sprite.RND.Next(range) + startDiam;
                int h = Sprite.RND.Next(range) + startDiam;
                int maxOffsetX = explosion.Image.Width - w;
                int maxOffsetY = explosion.Image.Height - h;
                int offsetX = Sprite.RND.Next(maxOffsetX);
                int offsetY = Sprite.RND.Next(maxOffsetY);
                Bitmap bmp = new Bitmap(w, h);
                Graphics g = Graphics.FromImage(bmp);
                using (g)
                {
                    try
                    {
                        g.DrawImageUnscaled(explosion.Image, -offsetX, -offsetY);
                    }
                    catch
                    {
                    }
                }
                _image = ImageUtils.Create32bppBitmap(bmp);
            }
            catch
            {
                //object in use exceptions sometimes
            }
        }

        //render
        public override void Render(Graphics g, SpriteSurface surface)
        {
            if (surface == null)
                return;
            _angle += _rotation;
            if (_angle < 0)
                _angle += 360;
            if (_angle > 360)
                _angle -= 360;
            _image = ImageUtils.RotateImage(_image, _angle);
            int x = (int)(Parent.X - surface.OffsetX + X - _image.Width / 2);
            int y = (int)(Parent.Y - surface.OffsetY + Y - _image.Height / 2);
            g.DrawImageUnscaled(_image, x, y);
        }

        //private members
        private float _angle = 0;
        private Image _image;
        private float _rotation;
    }
}
